
// JavaScript Document
var collection_save_state = add_attation_state = product_save_state = showcollect_state = 1;
if (Function.bind === undefined) {
    Function.prototype.bind = function(obj){
    
        if (typeof obj !== 'object') {
            throw 'obj is not an object';
        }
        var self = this, args = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : null;
        
        return function(){
            if (!args && !arguments.length) 
                return self.call(obj);
            if (args && arguments.length) 
                return self.apply(obj, Array.prototype.slice.call(arguments, 0).concat(args));
            return self.apply(obj, args || arguments);
        }
    };
}

var cookie = {
    encode: encodeURIComponent,
    decode: decodeURIComponent,
    get: function(name){
        var ckPatern = /([^=]+)=([^=]+)/, ckPart = '', ckStr = document.cookie, arr = ckStr.split(/;\s/);
        
        for (var i = 0, l = arr.length; i < l; i++) {
            ckPart = arr[i].match(ckPatern);
            if (ckPart) {
                var ckName = ckPart[1];
                if ((ckName === name) || (ckName === this.decode(name))) {
                    return this.decode(ckPart[2]);
                }
            }
        }
        
        return null;
        
    },
    set: function(name, value, options){
        var ckText = this.encode(name) + '=' + this.encode(value);
        
        if (typeof options == 'object') {
        
            if (options.expires instanceof Date) {
                ckText += '; expires=' + options.expires.toUTCString()
            }
            if (typeof options.path == 'string') {
                ckText += '; path=' + options.path;
            }
            if (typeof options.domain == 'string') {
                ckText += '; domain=' + options.domain;
            }
        }
        document.cookie = ckText;
    }
};

/*
 * function login(urlsObj, options)
 *
 */
function login(urlsObj, options){
	if(arguments.length===0){
		var options={};
	}else if(arguments.length===1){
		var options=arguments[arguments.length-1];
	}
	
    var jsonData; //every time login or exit successfully,assign value to the share data
    var mainLoginPort = $('#loginPortId_01'), loginBtn = $('#loginBtnId'), exitBtn = $('#exit'), mask = $('<div class="mask"></div>');
	
	mask.css({
		'display':'none',
		'opacity':'0.6',
		'background-color':'#000',
		'z-index':5000
	});
	$(document.body).append(mask);
    
    var login_before = $('#login_before'), login_after = $('#login_after'), username_txt = $('#username_txt');
    
    var loginBox = $('#loginBoxId'), loginCloseBtn = $('#loginCloseBtnId');
    var userNameIpt = $('#userNameId'), passwordIpt = $('#passwordId');
    
    var loadingBox = $('#loadingBoxId');
    
    var errorBox = $('#errorBoxId'), errorReturnBtn = $('#errorReturnBtnId'), errorCloseBtn = $('#errorCloseBtn'), errorInfo = $('#errorInfo');
    
    mainLoginPort.bind('click', function(e){
        e.preventDefault();
        showLoginBox();
        showMask();
    });
    (function setLoginPorts(){
        var args = arguments[0];
        for (var i = 0; i < args.length; i++) {
            var loginPort = $(args[i]);
            if (loginPort.length > 0) {
                loginPort.bind('click', function(e){
					if(hasLogin()){
						return false;
					}
                    e.preventDefault();
                    showLoginBox();
                    showMask();
                });
            }
        }
    })(options.loginPorts||[]);
    /*
     var iframe = $('<iframe frameborder="0"><html style="background:#000;"><body style="background:#000;"></body></html></iframe>');
     
     iframe.css('height', document.documentElement.scrollHeight);
     iframe.css('width', window.screen.width);
     mask.append(iframe);
     */
    mask.css('height', document.documentElement.scrollHeight);
    mask.css('width', document.documentElement.clientWidth);

    //modiby by yubin edit wh
    //loadingBox.css({width:'200px', height:'200px'});
    //errorBox.css({width:'200px', height:'200px'});
    
    
    (function setPosition(){
        var args = Array.prototype.slice.call(arguments, 0);
        for (var i = 0; i < args.length; i++) {
            args[i].css('left', parseInt(document.documentElement.scrollLeft) + (parseInt(document.documentElement.clientWidth) - loginBox.width()) / 2 + 'px');
            args[i].css('top', parseInt(document.documentElement.scrollTop) + (parseInt(document.documentElement.clientHeight) - loginBox.height()) / 2 + 'px');
        }
        
        $(window).bind('scroll', function(){
            for (var i = 0; i < args.length; i++) {
                args[i].css('left', parseInt(document.documentElement.scrollLeft) + (parseInt(document.documentElement.clientWidth) - loginBox.width()) / 2 + 'px');
                args[i].css('top', parseInt(document.documentElement.scrollTop||document.body.scrollTop) + (parseInt(document.documentElement.clientHeight) - loginBox.height()) / 2 + 'px');
            }
        });
        
    })(loginBox, loadingBox, errorBox);
    
    
    function showLoginBox(){
        //焦点绑到userNameId上
        setTimeout("$('#userNameId').focus()", 1);
        $(".login-title").html('你需要先登录才能继续本操作');
        loginBox.bind('keyup', function(event)
        {
           if(event.keyCode=="13")
           {
               loginBtn.click();
           }
        });

        loginBox.show();
    }
    
    function hideLoginBox(){
        loginBox.hide();
    }
    
    function showMask(){
		mask.css({
			'position':'absolute',
			'top':0,
			'left':0,
			'opacity':0.6
		});
        mask.show();
    }
    
    function hideMask(){
        mask.hide();
        document.body.style.overflow = '';
    }
    
    function showLoadingBox(){
        loadingBox.show();
    }
    
    function hideLoadingBox(){
        loadingBox.hide();
    }
    
    function updateLoginInfo(infoObj){
    
        login_before.hide();
        login_after.show();
        username_txt.html(infoObj.voguename);

        $_CNC_COMMON.login();
    }
    
    function resetLoginInfo(infoObj){
        login_before.show();
        login_after.hide();
        username_txt.html('Mr Dog~!');//^_^ ^_^
    }
    
    function setCookieInfo(jssrc){
        var jsSrcArry = jssrc.split(',');
        for (var i = 0; i < jsSrcArry.length; i++) {
            var script = document.createElement('script');
            script.src = jsSrcArry[i];
            script.type = 'text/javascript';
            document.body.appendChild(script);
        }
    }
    
    function resetCookieInfo(jssrc){
        var jsSrcArry = jssrc.split(',');
        for (var i = 0; i < jsSrcArry.length; i++) {
            var script = document.createElement('script');
            script.src = jsSrcArry[i];
            script.type = 'text/javascript';
            document.body.appendChild(script);
        }
    }
    
	function hasLogin(){
		var ckValue = cookie.get('voguebbsuid');
		if (!!ckValue && ckValue !== 'deleted') {
			return true
		}
		return false;
	}
	
	
    function checkCookie(data){
        if (data === undefined) {
        
            data = {
                'voguename': cookie.get('voguebbsnickname')
            };
        }
        
        if (hasLogin()) {
            updateLoginInfo(data)
            if (!!options&&typeof options.updateUserInfoCallback === 'function') {
                options.updateUserInfoCallback.bind(data)();
            }
        }
		/*
        else {
            resetLoginInfo(data);
            if (!!options&&typeof options.resetUserInfoCallback === 'function') {
                options.resetUserInfoCallback.bind(data)();
            }
        }
		*/
        
    }
    
    checkCookie(jsonData);
    
    function showErroInfo(msg){
        errorBox.show();
        if (typeof msg === 'string') {
            errorInfo.html(msg);
        }
    }

    function showLoginTitle(msg)
    {
        $(".login-title").html('<font style="color:red;">' + msg + '</font>');
    }
    
    function hideErroInfo(){
        errorBox.hide();
    }
    
    loginBtn.bind('click', function(e){
		e.preventDefault();
        var userName = userNameIpt.attr('value'), password = passwordIpt.attr('value');
        
        //hideLoginBox();
        //showLoadingBox();
        if(!userName || !password)
        {
            showLoginTitle('用户名或密码错误');
            return;
        }
        showLoginTitle('登录请求中...');
        var date = new Date();
        $.ajax({
            type: 'post',
            url: !!urlsObj&&!!urlsObj.loginUrl && typeof urlsObj.loginUrl === 'string' ? urlsObj.loginUrl : 'http://www.vogue.com.cn/api/www/proxy_login.php',
            dataType: 'json',
            data: 'voguename=' + userName + '&voguepassword=' + password + '&time='+date.getTime(),
            success: function(data, textStatus, jqXHR){
            
                jsonData = data;
                if (jsonData.status == true) {
                    showLoginTitle('登录成功');
                    //hideLoadingBox();
                    hideLoginBox();
                    hideMask();
                    updateLoginInfo(jsonData);
                    setCookieInfo(jsonData.jssrc);

                    if (!!options&&typeof options.updateUserInfoCallback === 'function') {
                        options.updateUserInfoCallback.bind(jsonData)();
                    }

                    
                }
                else {

                    //hideLoadingBox();
                    showLoginTitle(jsonData.msg);
                    //showErroInfo(jsonData.msg);
                }
                
            },
            error: function(jqXHR, textStatus, errorThrown){
                showLoginTitle('登录失败');
                //hideLoadingBox();
                //showErroInfo('ajax error:' + textStatus);
                //showLoginTitle('ajax error:' + textStatus);
                
            }
            
        });
    });
    
    loginCloseBtn.bind('click', function(e){
        e.preventDefault();
        hideLoginBox();
        hideMask();
        collection_save_state = add_attation_state = product_save_state = showcollect_state = 1;
        $('.overlay').hide().remove();
    });
    
    errorReturnBtn.bind('click', function(e){
        e.preventDefault();
        hideErroInfo();
        showLoginBox();
    });
    
    errorCloseBtn.bind('click', function(e){
        e.preventDefault();
        hideErroInfo();
        hideMask();
        $('.overlay').hide().remove();
    });
    
    exitBtn.bind('click', function(e){
		e.preventDefault();
        var userName = userNameIpt.attr('value'), password = passwordIpt.attr('value');
        
        //showLoadingBox();
        
        $.ajax({
            type: 'post',
            url: !!urlsObj&&!!urlsObj.exitUrl && typeof urlsObj.exitUrl === 'string' ? urlsObj.exitUrl : 'http://www.vogue.com.cn/api/www/proxy_exit.php',
            dataType: 'json',
            success: function(data, textStatus, jqXHR){
            
                jsonData = data;
                if (jsonData.status == true) {
                    //hideLoadingBox();
                    
                    resetLoginInfo(jsonData);
                    if (!!options&&typeof options.resetUserInfoCallback === 'function') {
                        options.resetUserInfoCallback.bind(jsonData)();
                    }
                    resetCookieInfo(jsonData.jssrc);
                }
                else {
                    //hideLoadingBox();//alert(jsonData.msg);
                    showErroInfo(jsonData.msg);
                }
                
            },
            error: function(jqXHR, textStatus, errorThrown){
                //hideLoadingBox();
                showErroInfo('ajax error:' + textStatus);
                
            }
            
        });
    });
    
}



